package com.learn.netty.websocket;

import com.learn.netty.heartbeat.HeartBeatNettyHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class WebsocketServer {

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    /**
                     * 基于http协议 使用http的编码和解码器
                     */
                    pipeline.addLast(new HttpServerCodec());

                    /**
                     * 是以块方式写 添加ChunkedWriteHandler 处理器
                     */
                    pipeline.addLast(new ChunkedWriteHandler());
                    /**
                     * 说明
                     * 1. http传输时分段HttpObjectAggregator 就是可以将多个段聚合
                     * 2. 这就是为什么当浏览器发送大量数据时，就会发出多次http请求
                     */
                    pipeline.addLast(new HttpObjectAggregator(8192));
                    /**
                     * 说明
                     * 1. 对应websocket 它的数据是以帧（frame）的形式传递
                     * 2. 可以看到 WebSocketFrame下面有6个子类
                     * 3.浏览器请求时 ws://localhost:8999/hello 表示请求的uri
                     * 4. WebSocketServerProtocolHandler 核心功能是 将http无状态协议升级为ws协议 保持长连接
                     */
                    pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

                    pipeline.addLast(new WebsocketHandler());

                }
            });

            ChannelFuture sync = bootstrap.bind(8999).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
